<template>
	<h1>{{ user.age }}</h1>
	<button type="button" @click="increase">Increase</button>
	<button type="button" :disabled="buttonStatus.disabled">
		{{ buttonStatus.text }}
	</button>
</template>

<script lang="ts">
import { defineComponent, reactive, ref, computed, watch } from 'vue'
interface Person {
	name: string
	age: number
}
interface ButtonStatus {
	text: string
	disabled: boolean
}
export default defineComponent({
	name: 'WatchDemo',
	setup() {
		// 推荐原始类型用 ref,引用类型用 reactive
		const count = ref<number | string>(0)
		const user = reactive<Person>({
			name: '李子一',
			age: 3
		})

		watch(
			count,
			(newValue, oldValue) => {
				console.log('old count', oldValue)
				console.log('new count', newValue)
				document.title = `目前的点击次数是: ${newValue}`
			},
			{ immediate: true }
		)

		// getter function
		watch(
			() => user.age, // 监听响应式对象的一个属性
			(newValue, oldValue) => {
				console.log('old age', oldValue)
				console.log('new age', newValue)
				document.title = `目前的点击次数是: ${newValue}`
			}
		)

		watch(user, (newValue, oldValue) => {
			console.log('old age', oldValue)
			console.log('new age', newValue)
			document.title = `目前的点击次数是: ${newValue}`
		})

		watch([count, () => user.age], (newValue, oldValue) => {
			console.log('old age', oldValue)
			console.log('new age', newValue)
			document.title = `目前的点击次数是: ${newValue[0]}`
		})

		const increase = () => {
			if (typeof count.value === 'number') {
				count.value++
			}
			user.age++
		}

		const buttonStatus = computed<ButtonStatus>(() => {
			return {
				text: user.age >= 10 ? '可以参与' : '未满 10 岁不可参加',
				disabled: user.age < 10
			}
		})

		return { count, increase, user, buttonStatus }
	}
})
</script>
<style lang="scss" scoped></style>
